package com.fg.cloud.factory.controller.factory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fg.cloud.common.PageUtils;
import com.fg.cloud.common.StatusCode;
import com.fg.cloud.common.encrypt.Encrypt;
import com.fg.cloud.common.quantity.ResultType;
import com.fg.cloud.common.validate.LongUtils;
import com.fg.cloud.framework.controller.BaseController;
import com.fg.cloud.manager.entry.factory.FactoryUserEntity;
import com.fg.cloud.manager.entry.factory.vo.FactoryUserVo;
import com.fg.cloud.manager.entry.system.vo.RoleVo;
import com.fg.cloud.manager.service.agency.AgencyAreaService;
import com.fg.cloud.manager.service.factory.FactoryUserService;

/**
 * Description:厂商用户信息控制
 * 
 * @author shaoqiping
 * @date 2017年8月3日下午5:43:52
 */
@Controller
@RequestMapping("/factoryUser")
public class FactoryUserController extends BaseController {

	@Autowired
	private FactoryUserService factoryUserService;
	@Autowired
	private AgencyAreaService areaService;
	/**
	 * Description:厂商用户详细信息
	 * 
	 * @param request
	 * @param session
	 * @param paramsEntity
	 * @author shaoqiping
	 * @date 2017年8月3日下午2:26:13
	 */
	@RequestMapping(value = "/openPage", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public void openPage(HttpServletRequest request, HttpServletResponse response, Long id) {
		try {
			if (LongUtils.isEmpty(id) || id == null) {
				doResult(response, false, StatusCode.LACKVALUE, null, ResultType.CHOOSE_INFO);
				return;
			}
			FactoryUserEntity paramsEntity = factoryUserService.find(id);
			if (paramsEntity == null || !paramsEntity.getFacId().equals(getCurrentFactoryUser().getFacId())) {
				doResult(response, false, StatusCode.FINDERROR, null, ResultType.FIND_FAULT);
				return;
			}
			paramsEntity.setPassword(null);
			doResult(response, true, StatusCode.FINDSUCCESS, paramsEntity, ResultType.FIND_SUCCESS);

		} catch (Exception e) {
			e.printStackTrace();
			doResult(response, false, StatusCode.EXCEPTIONERROR, null, e.getMessage());
		}
	}

	/**
	 * Description:分页查询
	 * 
	 * @param request
	 * @param response
	 * @param page
	 * @param rows
	 * @param sort
	 * @param order
	 * @param factoryUser
	 * @author shaoqiping
	 * @date 2017年8月3日下午4:43:14
	 */
	@RequestMapping(value = "/findList", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public void findList(HttpServletRequest request, HttpServletResponse response, Integer page, Integer rows,
			String sort, String order, @RequestParam(required = false) String filterText) {
		try {
			// page默认为1 rows默认为10
			if (page == null || page <= 0) {
				page = 1;
			}
			if (rows == null || rows <= 0) {
				rows = 10;
			}
			PageUtils<FactoryUserVo> pageinfo = new PageUtils<FactoryUserVo>(page, rows, sort, order);
			Map<String, Object> condition = pageinfo.getCondition();
			condition.put("filterText", filterText);
			condition.put("facId", getCurrentFactoryUser().getFacId());
			pageinfo.setCondition(condition);

			factoryUserService.findList(pageinfo);
			doResult(response, true, StatusCode.FINDSUCCESS, pageinfo, ResultType.FIND_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			doResult(response, false, StatusCode.EXCEPTIONERROR, null, e.getMessage());
		}
	}

	/**
	 * Description:新增/保存厂商用户信息
	 * 
	 * @param request
	 * @param response
	 * @param user
	 * @param imgFile
	 * @author shaoqiping
	 * @date 2017年8月3日上午10:31:48
	 */
	@RequestMapping(value = "/saveOrUpdate", method = RequestMethod.POST)
	@ResponseBody
	public void saveOrUpdate(HttpServletRequest request, HttpServletResponse response, FactoryUserEntity user) {
		try {
			if(user==null||StringUtils.isEmpty(user.getUserName())){
				doResult(response, false, StatusCode.LACKVALUE, null, "请填写必要信息");
				return;
			}
			user.setFacId(getCurrentFactoryUser().getFacId());
			// id为空新增、不为空保存
			if (LongUtils.isEmpty(user.getId())) {
				FactoryUserEntity temp = factoryUserService.selectUserByUserName(user.getUserName(),user.getFacId());
				if (temp != null) {
					doResult(response, false, StatusCode.SAVEERROR, null, ResultType.USER_REPEAT);
					return;
				}
				setCreateInfo(user, request);
				setUpdateInfo(user, request);
				user.setUserType(1);
				user.setPassword(Encrypt.md5(user.getPassword()));
				factoryUserService.insertSelective(user);
				doResult(response, true, StatusCode.SAVESUCCESS, null, ResultType.ADD_SUCCESS);
			} else {
				FactoryUserEntity temp = factoryUserService.selectUserByUserName(user.getUserName(),user.getFacId());
				if (temp != null && !temp.getId().equals(user.getId())) {
					doResult(response, false, StatusCode.SAVEERROR, null, ResultType.USER_REPEAT);
					return;
				}
				setUpdateInfo(user, request);
				user.setPassword(Encrypt.md5(user.getPassword()));
				factoryUserService.updateByPrimaryKeySelective(user);
				doResult(response, true, StatusCode.SAVESUCCESS, null, ResultType.SAVE_SUCCESS);
			}
		} catch (Exception e) {
			e.printStackTrace();
			doResult(response, false, StatusCode.EXCEPTIONERROR, null, e.getMessage());
		}
	}

	/**
	 * Description:重置密码
	 * 
	 * @param request
	 * @param response
	 * @param user
	 * @author shaoqiping
	 * @date 2017年8月3日下午5:25:55
	 */
	@RequestMapping(value = "/resetPw", method = RequestMethod.POST)
	@ResponseBody
	public void resetPassword(HttpServletRequest request, HttpServletResponse response, FactoryUserEntity user) {
		try {
			if (LongUtils.isEmpty(user.getId()) || user == null) {
				doResult(response, false, StatusCode.LACKVALUE, null, ResultType.CHOOSE_INFO);
				return;
			}
			FactoryUserEntity temp = factoryUserService.findToCheck(user.getId());
			if (temp == null || !temp.getFacId().equals(getCurrentFactoryUser().getFacId())) {
				doResult(response, false, StatusCode.SAVEERROR, null, ResultType.SAVE_FAULT);
				return;
			}
			setUpdateInfo(user, request);
			user.setPassword(Encrypt.md5("123456"));
			factoryUserService.updateByPrimaryKeySelective(user);
			doResult(response, true, StatusCode.SAVESUCCESS, null, ResultType.SAVE_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			doResult(response, false, StatusCode.EXCEPTIONERROR, null, e.getMessage());
		}
	}

	/**
	 * Description:删除用户（逻辑删除）
	 * 
	 * @param request
	 * @param response
	 * @param userIds
	 * @author shaoqiping
	 * @date 2017年8月3日下午2:58:55
	 */
	@RequestMapping(value = "/deletes", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public void deletes(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "ids") String userIds) {
		try {
			if (userIds == null || StringUtils.isEmpty(userIds)) {
				doResult(response, false, StatusCode.LACKVALUE, null, ResultType.CHOOSE_INFO);
				return;
			}
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("ids", userIds);
			map.put("facId", getCurrentFactoryUser().getFacId());
			boolean temp = factoryUserService.deletes(map);
			if (temp) {
				doResult(response, true, StatusCode.REMOVESUCCESS, null, ResultType.REMOVE_SUCCESS);
			} else {
				doResult(response, false, StatusCode.REMOVEERROR, null, ResultType.REMOVE_FAULT);
			}
		} catch (Exception e) {
			e.printStackTrace();
			doResult(response, false, StatusCode.EXCEPTIONERROR, null, e.getMessage());
		}
	}

	/**
	 * Description:查询用户的角色
	 * 
	 * @param request
	 * @param response
	 * @param userEntity
	 * @author shaoqiping
	 * @date 2017年8月10日下午3:22:45
	 */
	@RequestMapping(value = "/findUserRoles", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public void findUserRoles(HttpServletRequest request, HttpServletResponse response, Long id) {
		try {
			if (id == null || LongUtils.isEmpty(id)) {
				doResult(response, false, StatusCode.LACKVALUE, null, ResultType.CHOOSE_INFO);
				return;
			}
			FactoryUserEntity paramsEntity = factoryUserService.findToCheck(id);
			if (paramsEntity == null || !paramsEntity.getFacId().equals( getCurrentFactoryUser().getFacId())) {
				doResult(response, false, StatusCode.FINDERROR, null, ResultType.FIND_FAULT);
				return;
			}
			List<RoleVo> roleList = factoryUserService.findByFacId(id, paramsEntity.getFacId());
			if (roleList == null || roleList.size() <= 0) {
				doResult(response, true, StatusCode.FINDERROR, null, ResultType.FIND_NULL);
				return;
			}
			doResult(response, true, StatusCode.FINDSUCCESS, roleList, ResultType.FIND_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			doResult(response, false, StatusCode.EXCEPTIONERROR, null, e.getMessage());
		}
	}

	/**
	 * Description:更新用户的角色
	 * 
	 * @param request
	 * @param response
	 * @param userId
	 * @param roleArray
	 * @author shaoqiping
	 * @date 2017年8月10日下午3:25:45
	 */
	@RequestMapping(value = "/updateUserRoles", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public void updateUserRoles(HttpServletRequest request, HttpServletResponse response, Long id, String roleArray) {
		try {
			if (id == null || LongUtils.isEmpty(id) || roleArray == null) {
				doResult(response, false, StatusCode.LACKVALUE, null, ResultType.CHOOSE_INFO);
				return;
			}
			FactoryUserEntity paramsEntity = factoryUserService.findToCheck(id);
			if (paramsEntity == null || !paramsEntity.getFacId().equals(getCurrentFactoryUser().getFacId())) {
				doResult(response, false, StatusCode.SAVEERROR, null, ResultType.SAVE_FAULT);
				return;
			}
			boolean flag = factoryUserService.updateUserRoles(id, roleArray);
			doResult(response, flag, flag ? StatusCode.SAVESUCCESS : StatusCode.SAVEERROR, null,
					flag ? ResultType.SAVE_SUCCESS : ResultType.SAVE_FAULT);
		} catch (Exception e) {
			e.printStackTrace();
			doResult(response, false, StatusCode.EXCEPTIONERROR, null, e.getMessage());
		}
	}
	

	/**
	 * Description:更新用户的区域
	 * 
	 * @param request
	 * @param response
	 * @param userId
	 * @param roleArray
	 * @author shaoqiping
	 * @date 2017年8月10日下午3:25:45
	 */
	@RequestMapping(value = "/updateUserAreas", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public void updateUserAreas(HttpServletRequest request, HttpServletResponse response, Long id, String areaArray) {
		try {
			if (id == null || LongUtils.isEmpty(id) || areaArray == null || StringUtils.isEmpty(areaArray)) {
				doResult(response, false, StatusCode.LACKVALUE, null, ResultType.CHOOSE_INFO);
				return;
			}
			FactoryUserEntity paramsEntity = factoryUserService.findToCheck(id);
			if (paramsEntity == null || !paramsEntity.getFacId().equals(getCurrentFactoryUser().getFacId())) {
				doResult(response, false, StatusCode.SAVEERROR, null, ResultType.SAVE_FAULT);
				return;
			}
			boolean flag = areaService.updateUserAreas(id, areaArray);
			doResult(response, flag, flag ? StatusCode.SAVESUCCESS : StatusCode.SAVEERROR, null,
					flag ? ResultType.SAVE_SUCCESS : ResultType.SAVE_FAULT);
		} catch (Exception e) {
			e.printStackTrace();
			doResult(response, false, StatusCode.EXCEPTIONERROR, null, e.getMessage());
		}
	}
}
